package fictional.GUI;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JWindow;

/**
 * A popup window which shows up whenever a task is
 * running and the window is busy.
 */
public class BusyIconPopup
{
    private final Icon[] busyIcons = new Icon[12];
    private final Timer busyIconTimer;
    private int busyIconIndex = 0;
    JLabel busyIconLabel;
    JWindow window;

    public BusyIconPopup()
    {
        busyIconLabel = new JLabel();
        
        window = new JWindow();
        
        JPanel busyPanel = new JPanel();
        busyPanel.setBackground(new java.awt.Color(255, 255, 255));
        busyPanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        busyPanel.setLayout(new java.awt.GridBagLayout());
        busyPanel.add(busyIconLabel, new java.awt.GridBagConstraints());
        
        window.setBackground(Color.white);

        int busyAnimationRate = 30;
        for (int i = 1; i <= busyIcons.length; i++)
        {
            busyIcons[i - 1] = new ImageIcon(getClass().getResource("resources/newBusyIcons/busyIcon_b" + i + ".png"));
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                busyIconLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });

        window.getContentPane().add(busyPanel, BorderLayout.CENTER);
        window.setAlwaysOnTop(true);

        // Set initial size
        window.setSize(120, 120);
        window.setLocationRelativeTo(null);
    }
    
    public void start()
    {
        // Show the window
        window.setVisible(true);
        
        if (!busyIconTimer.isRunning())
        {
            busyIconLabel.setIcon(busyIcons[0]);
            busyIconIndex = 0;
            busyIconTimer.start();
        }
    }
    
    public void stop()
    {
        busyIconTimer.stop();
        window.setVisible(false);
    }
}
